<template>
  <el-form status-icon ref="pwd" :model="pwd" :rules="rules" label-width="140px">
    <el-form-item label="原密码" prop="password">
      <el-input type="password" v-model="pwd.password"></el-input>
    </el-form-item>
    <el-form-item label="新密码" prop="newPassword">
      <el-input type="password" v-model="pwd.newPassword"></el-input>
    </el-form-item>
    <el-form-item label="请再次输入新密码" prop="rePassword">
      <el-input type="password" v-model="pwd.rePassword"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button style="width: 320px" round type="primary" @click="onSubmit('pwd')">更改密码</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  name: "UpdatePwd",
  data() {
    let oldPwd = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        this.axios
          .get("/user/front/checkPwd?pwd=" + this.pwd.password)
          .then(res => {
            if (res.data.status === 500) {
              callback(new Error(res.data.msg));
            }
            callback();
          });
      }
    };
    let validatePass = (rule, value, callback) => {
      console.log(value);
      if (value === "") {
        callback(new Error("请输入新密码"));
      } else {
        if (this.pwd.rePassword !== "") {
          this.$refs.pwd.validateField("rePassword");
        }
        callback();
      }
    };
    let validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.pwd.newPassword) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      pwd: {
        password: "",
        newPassword: "",
        rePassword: ""
      },
      rules: {
        password: [{ validator: oldPwd, trigger: "blur" }],
        newPassword: [{ validator: validatePass, trigger: ["change", "blur"] }],
        rePassword: [{ validator: validatePass2, trigger: ["change", "blur"] }]
      }
    };
  },
  methods: {
    onSubmit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let parmaes = {
            pwd: this.pwd.password,
            newPwd: this.pwd.newPassword
          };
          this.$myPut(this, "/user/front/updatePwd", null, parmaes);
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    }
  }
};
</script>

<style scoped>
</style>